package com.网络编程.net.http;

/**
 * @author liyiruo
 * @Description
 * @Date 2024/5/22 下午3:38
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpGetByURL {
    public static void main(String[] args) {
        try {
            // 目标 URL
            String url = "https://api.example.com/data";

            // 创建 URL 对象
            URL apiUrl = new URL(url);

            // 创建 HttpURLConnection 对象
            HttpURLConnection connection = (HttpURLConnection) apiUrl.openConnection();

            // 设置请求方法为 GET
            connection.setRequestMethod("GET");

            // 发送 GET 请求
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = reader.readLine()) != null) {
                response.append(inputLine);
            }
            reader.close();

            // 输出响应内容
            System.out.println("Response Body: " + response.toString());

            // 关闭连接
            connection.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

